package springboot.common_utils;

import cn.hutool.core.lang.UUID;

import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;


/**
 * @author daiqiang
 * @since 2024/2/2-9:04
 */
public class JWTUtils {
    // 有效期
    private static final long JWT_EXPIRE = 30 * 60 * 1000L; // 半小时
    // 令牌密钥
   // private static final String JWT_KEY = UUID.randomUUID().toString(); // 使用UUID生成一个随机密钥
    private static final String JWT_KEY ="123456";
    private static final String JWT_ISSUER = "system"; // 发行者
    private static final String JWT_ALGORITHM = "HS256"; // 签名算法
    private static final String JWT_ENCODING = "UTF-8"; // 编码格式
    private static final String JWT_SECRET = "password"; // 密钥
    private static final String JWT_SECRET_SALT = "salt"; // 密钥盐值
    private static final int JWT_SECRET_SALT_LENGTH = 16; // 密钥盐值长度
    private static final String JWT_SECRET_SALT_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // 密钥盐值字符集

    public static String    createToken(Object data) {
        // 当前时间
        long currentTime = System.currentTimeMillis();
        // 过期时间
        long expTime = currentTime + JWT_EXPIRE;
        // 构建jwt
        JwtBuilder builder = Jwts.builder()
                .setId(UUID.randomUUID() + "")
                .setSubject(JSON.toJSONString(data))
                .setIssuer(JWT_ISSUER)
                .setIssuedAt(new Date(currentTime))
                .signWith(SignatureAlgorithm.HS256, encodeSecret(JWT_KEY))
                .setExpiration(new Date(expTime));
        return builder.compact();
    }

    private static SecretKey encodeSecret(String key) {
        byte[] encodedKey = Base64.getEncoder().encode(key.getBytes());
        // 创建AES密钥
        return new SecretKeySpec(encodedKey, "AES");
    }
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(encodeSecret(JWT_KEY))
                .parseClaimsJws(token)
                .getBody();
    }

    public static <T> T parseToken(String token, Class<T> clazz) {
        Claims body = Jwts.parser()
                .setSigningKey(encodeSecret(JWT_KEY))
                .parseClaimsJws(token)
                .getBody();
        return JSON.parseObject(body.getSubject(), clazz);
    }


}
